//
//  ChatListViewController.m
//  PhotographyStudi
//
//  Created by 叶一枫 on 2017/5/17.
//  Copyright © 2017年 叶一枫. All rights reserved.
//

#import "ChatListViewController.h"

@interface ChatListViewController ()<UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate>

@property(nonatomic,strong)UISearchController *searchController;
@property (nonatomic,strong)NSMutableArray *currentArr;//当前会话列表数组
@property (nonatomic,strong)NSMutableArray *resultArray;//搜索数组
@property (nonatomic,assign)BOOL isSearching;

@end

@implementation ChatListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showConnectingStatusOnNavigatorBar = YES;
    self.conversationListTableView.tableFooterView = [[UIView alloc]init];
    
    RCUserInfo *mySelf = [[RCUserInfo alloc]initWithUserId:[User shareUser].uid name:[User shareUser].uname portrait:[User shareUser].userAvatar];
    [RCIM sharedRCIM].currentUserInfo = mySelf;
    
    [self initSearchController];
}

-(NSMutableArray *)resultArray{
    if (!_resultArray) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;
}

-(void)initSearchController{
    
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.barTintColor = [UIColor colorWithHexString:@""];
    self.searchController.delegate = self;
    self.searchController.searchBar.delegate = self;
    self.searchController.searchBar.placeholder = @"搜索";
    self.searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
    self.conversationListTableView.tableHeaderView = self.searchController.searchBar;
}

//storyboard 初始化方法
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        //设置要显示的会话类型
        [self setDisplayConversationTypes:@[
                                            @(ConversationType_PRIVATE),
                                            @(ConversationType_DISCUSSION),
                                            @(ConversationType_APPSERVICE),
                                            @(ConversationType_PUBLICSERVICE),
                                            @(ConversationType_GROUP),
                                            @(ConversationType_SYSTEM)
                                            ]];
        
        //聚合会话类型
        [self setCollectionConversationType:@[ @(ConversationType_DISCUSSION) ]];
        
    }
    return self;
}

-(NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource{
    if (!self.currentArr) {
        self.currentArr = dataSource;
    }
    return self.isSearching?self.resultArray:dataSource ;
}

//重写RCConversationListViewController的onSelectedTableRow事件
- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath {
    
    if (conversationModelType == 1) {
        ChatViewController *conversationVC = [[ChatViewController alloc]init];
        conversationVC.conversationType = model.conversationType;
        conversationVC.targetId = model.targetId;
        conversationVC.title = model.conversationTitle;
        [self.navigationController pushViewController:conversationVC animated:YES];
        
    }else{
        ChatListViewController *chatVC = [[ChatListViewController alloc] init];
        chatVC.title = model.conversationTitle;
        NSArray *array = [NSArray arrayWithObject:[NSNumber numberWithInt:model.conversationType]];
        [chatVC setDisplayConversationTypes:array];
        [chatVC setCollectionConversationType:nil];
        chatVC.isEnteredToCollectionViewController = YES;
        [self.navigationController pushViewController:chatVC animated:YES];
    }
    
    dispatch_after(
                   dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                       [self refreshConversationTableViewIfNeeded];
                   });
}

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if ([searchText isEqualToString:@""]) {
        self.isSearching = NO;
    }else{
        self.isSearching = YES;
    }
    //需要事先情况存放搜索结果的数组
    [self.resultArray removeAllObjects];
    
    //加个多线程，否则数量量大的时候，有明显的卡顿现象
    //这里最好放在数据库里面再进行搜索，效率会更快一些
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        if (searchText!=nil && searchText.length>0) {
            
            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
            for (RCConversationModel *model in self.currentArr) {
                for (NSString *text in @[model.conversationTitle]) {
                    NSString *pinyin = [[BSTool sharedBSTool]transformToPinyin:text];
                    if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
                        if (![self.resultArray containsObject:model]) {
                            [self.resultArray addObject:model];
                        }
                    }
                }
            }
        }else{
            self.resultArray = [NSMutableArray arrayWithArray:self.currentArr];
        }
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self willReloadTableData:self.resultArray];
            [self.conversationListTableView reloadData];
        });
    });
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
